package com.evil.common.core.util;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author liyang
 * @date 2023-01-15 21:07
 */
@Slf4j
public class GenerateUtil extends RandomUtil {

    /**
     * 生成key
     *
     * @return String
     */
    public static String generateKey(Type type, Function<String, Boolean> checkDuplicateFun) {
        // 生成应用key
        String key = type.generateFunc().get();
        int frequency = 1;
        while (checkDuplicateFun.apply(key)) {
            key = type.generateFunc().get();
            frequency++;
            if (frequency > 10) {
                log.error("【生成key】，当前次数：{}", frequency);
            }
        }
        return key;
    }

    public interface Type {
        Supplier<String> generateFunc();
    }

    public static class DefaultRandomType implements GenerateUtil.Type {

        @Override
        public Supplier<String> generateFunc() {
            return () -> RandomUtil.randomString(8);
        }
    }
}
